package com.party.mobile.web.controller.member;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.city.Area;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAddress;
import com.party.core.model.member.MemberAddressOutput;
import com.party.core.model.system.TargetType;
import com.party.core.service.city.IAreaService;
import com.party.core.service.member.IMemberAddressService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: 商城用户地址库
 * @Date:Created in 2017/9/12 0012 下午 18:21.
 */
@Controller
@Authorization
@RequestMapping("member/address")
public class AddressController {
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IMemberAddressService memberAddressService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private MemberBizService memberBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 列表
     *
     * @param page
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("list")
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult list(Page page, HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<MemberAddress> memberAddresses = memberAddressService.listPage(new MemberAddress(currentUser.getId()), page);
        List<MemberAddressOutput> outputs = LangUtils.transform(memberAddresses, new Function<MemberAddress, MemberAddressOutput>() {
            @Nullable
            @Override
            public MemberAddressOutput apply(@Nullable MemberAddress input) {
                MemberAddressOutput output = new MemberAddressOutput();
                output.setId(input.getId());
                output.setName(input.getName());
                output.setPhone(input.getPhone());
                output.setFullAddress(input.getShowAddress() + " " + input.getDetailAddress());
                return output;
            }
        });
        return AjaxResult.success(outputs, page);
    }

    /**
     * 详情
     *
     * @param addressId
     * @return
     */
    @ResponseBody
    @RequestMapping("addAddress")
    public AjaxResult addAddress(String addressId, HttpServletRequest request, Integer isBind) {
        Object member = currentUserBizService.getMember(request);
        Member currentUser = (Member) member;
        MemberAddress memberAddress = null;
        if (isBind != null && isBind == 1) {
            memberAddress = memberAddressService.getDefaultAddress(currentUser.getId());
        }
        if (StringUtils.isNotEmpty(addressId)) {
            memberAddress = memberAddressService.get(addressId);
        }
        if (memberAddress == null) {
            memberAddress = new MemberAddress();
            if (StringUtils.isEmpty(currentUser.getFullname())) {
                memberAddress.setName(currentUser.getRealname());
            } else {
                memberAddress.setName(currentUser.getFullname());
            }
            memberAddress.setPhone(currentUser.getMobile());
            if (StringUtils.isNotEmpty(currentUser.getCity())) {
                // 城市
                Area city = areaService.get(currentUser.getCity());
                memberAddress.setCityId(city.getId());
                // 省份
                Area province = areaService.get(city.getParentId());
                memberAddress.setProvinceId(province.getId());

                memberAddress.setShowAddress(province.getName() + " " + city.getName());
            }
        }
        return AjaxResult.success(memberAddress);
    }

    /**
     * 保存地址（不绑定手机）
     *
     * @param memberAddress 地址信息
     * @param result        验证结果
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("saveAddress")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult saveAddress(MemberAddress memberAddress, BindingResult result, HttpServletRequest request) {
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(11, allErros.get(0).getDefaultMessage());
        }
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            if (memberAddress.getDefaultAddress() == null) {
                memberAddress.setDefaultAddress(MemberAddress.NOT_DEFAULT_ADDRESS);
            }
            memberAddress.setMemberId(currentUser.getId());
            String showAddress = memberBizService.getShowAddress(memberAddress.getProvinceId(), memberAddress.getCityId(), memberAddress.getRegionId());
            memberAddress.setShowAddress(showAddress);
            if (StringUtils.isEmpty(memberAddress.getId())) {
                memberAddressService.insert(memberAddress);
            } else {
                memberAddressService.update(memberAddress);
            }

            // 如果當前地址是默認地址，將其他的地址取消默認地址
            if (memberAddress.getDefaultAddress().equals(MemberAddress.IS_DEFAULT_ADDRESS)) {
                List<MemberAddress> addresses = memberAddressService.list(new MemberAddress(currentUser.getId()));
                for (MemberAddress address : addresses) {
                    if (!memberAddress.getId().equals(address.getId())) {
                        address.setDefaultAddress(MemberAddress.NOT_DEFAULT_ADDRESS);
                        memberAddressService.update(address);
                    }
                }
            }
            return AjaxResult.success((Object) memberAddress.getId());
        } catch (Exception e) {
            logger.error("地址保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 保存地址（绑定手机）
     *
     * @param memberAddress 地址信息
     * @param result        验证结果
     * @param request
     * @param isBind        绑定用户信息
     * @param verifyCode    验证码
     * @param countryCode   区号
     * @return
     */
    @ResponseBody
    @RequestMapping("save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult save(MemberAddress memberAddress, BindingResult result, HttpServletRequest request,
                           Integer isBind, String verifyCode, String countryCode) {
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(11, allErros.get(0).getDefaultMessage());
        }
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Member member = memberService.get(currentUser.getId());
            if (isBind != null && isBind == 1) {
                currentUser = memberBizService.bindPhoneBiz2(memberAddress.getPhone(), verifyCode, countryCode, request);
                //如果字段为空 更新必要的用户信息
                Member newMember = new Member();
                newMember.setFullname(memberAddress.getName());
                newMember.setCity(memberAddress.getCityId());
                newMember.setCountryCode(countryCode);
                member = memberBizService.updateImportantInfo(newMember, memberService.get(currentUser.getId()));
            }

            if (memberAddress.getDefaultAddress() == null) {
                memberAddress.setDefaultAddress(MemberAddress.NOT_DEFAULT_ADDRESS);
            }
            memberAddress.setMemberId(member.getId());
            String showAddress = memberBizService.getShowAddress(memberAddress.getProvinceId(), memberAddress.getCityId(), memberAddress.getRegionId());
            memberAddress.setShowAddress(showAddress);
            if (StringUtils.isEmpty(memberAddress.getId())) {
                memberAddressService.insert(memberAddress);
            } else {
                memberAddressService.update(memberAddress);
            }

            // 如果當前地址是默認地址，將其他的地址取消默認地址
            if (memberAddress.getDefaultAddress().equals(MemberAddress.IS_DEFAULT_ADDRESS)) {
                List<MemberAddress> addresses = memberAddressService.list(new MemberAddress(member.getId()));
                for (MemberAddress address : addresses) {
                    if (!memberAddress.getId().equals(address.getId())) {
                        address.setDefaultAddress(MemberAddress.NOT_DEFAULT_ADDRESS);
                        memberAddressService.update(address);
                    }
                }
            }
            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("member", member);
            resultMap.put("addressId", memberAddress.getId());
            return AjaxResult.success(resultMap);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("地址保存异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
    }

    /**
     * 刪除地址
     *
     * @param addressId 地址編號
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String addressId) {
        if (StringUtils.isEmpty(addressId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        memberAddressService.delete(addressId);
        return AjaxResult.success();
    }

    /**
     * 更新为默认地址
     *
     * @param memberAddress
     * @return
     */
    @ResponseBody
    @RequestMapping("updateDefaultValue")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult updateDefaultValue(MemberAddress memberAddress, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            memberAddressService.cancelDefaultAddress(currentUser.getId());
            memberAddressService.update(memberAddress);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("更新默认地址异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "更新默认地址异常");
        }
    }

    /**
     * 检查用户有没有地址
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("checkAddress")
    public AjaxResult checkMemberAddress(HttpServletRequest request) {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<MemberAddress> addresses = memberAddressService.list(new MemberAddress(currentUser.getId()));
        if (addresses.size() > 0) {
            return AjaxResult.success(true);
        } else {
            return AjaxResult.success(false);
        }
    }
}
